package cn.jh.smartos.fragment

import android.content.*
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.LocalBroadcastManager
import android.text.TextUtils
import android.util.Log
import android.view.View
import cn.jh.smartos.*
import cn.jh.smartos.bean.ConnConfig
import cn.jh.smartos.client.ClientService
import cn.jh.smartos.service.SimpleHttpServer
import cn.jh.smartos.service.WebConfiguration
import cn.jh.smartos.utils.NetWorkKit
import cn.jh.smartos.utils.ToastU

import kotlinx.android.synthetic.main.fragment_setting.*
import java.lang.Exception

/**
 * Created by pjh on 18/3/12.
 */
class SettingF : BaseFragment() {
    override fun getLayoutId(): Int = R.layout.fragment_setting

    private val TAG = "SettingF"


    val wc = WebConfiguration()
    private var mServiceIntent: Intent? = null

    override fun initView() {
        if (ConnConfig.isService) {
            tv_title.text = "打开服务器"
            iv_state.setImageResource(R.drawable.service)
            et_ip.setText(NetWorkKit.getLocalIpAddress())
            et_ip.isEnabled = false
            btn_cancel.visibility = View.GONE
            val socket = SimpleHttpServer.getSocket()
            if (socket != null) {
                if (!socket.isClosed) {
                    Log.e(TAG, "init ----" + socket.localSocketAddress + socket.localPort)
                    btn_cancel.visibility = View.VISIBLE
                    et_port.setText("${socket.localPort}")
                    et_port.isEnabled = false
                    btn_ok.visibility = View.GONE
                    btn_cancel.setOnClickListener {
                        shs?.stopAsync()
                    }
                }
            }

            btn_ok.setOnClickListener {
                val txt_port = et_port.text.toString().trim()
//            val int_port = Integer.parseInt(txt_port)
                if (TextUtils.isEmpty(txt_port)) {
                    ToastU.showLongToast("请输入端口号")
                } else {

                    val port = Integer.parseInt(txt_port)
                    if (port > 1000 && port < 50000) {
                        wc.prot = port
                        wc.maxParallels = 50
                        shs = SimpleHttpServer(wc)
                        shs?.startAsync()
                    } else {
                        ToastU.showLongToast("请输入（1000 ~ 50000）的端口号")
                    }

                }

            }


        } else {      //客户端
            tv_title.text = "连接服务器"
            iv_state.setImageResource(R.drawable.client)
            et_ip.setText(ConnConfig.ip)
            et_port.setText(ConnConfig.port)
            btn_cancel.visibility = View.GONE

            btn_ok.setOnClickListener {
                val mac = et_ip.text.toString().trim()
                val port = et_port.text.toString().trim()
                if (TextUtils.isEmpty(mac)) {
                    ToastU.showToast("请输入服务器地址")
                    return@setOnClickListener
                } else if (TextUtils.isEmpty(port)) {
                    ToastU.showToast("请输入端口号")
                    return@setOnClickListener
                }
                ToastU.showToast("正在连接：" + mac)


                mServiceIntent?.putExtra("mac", mac)
                mServiceIntent?.putExtra("port", port)
                activity?.bindService(mServiceIntent, conn, Context.BIND_AUTO_CREATE)
                activity?.startService(mServiceIntent)
            }

        }




        mLocalBroadcastManager = LocalBroadcastManager.getInstance(App.context)
        mServiceIntent = Intent(App.context, ClientService::class.java)
        mIntentFilter = IntentFilter()
        mIntentFilter?.addAction(ClientService.HEART_BEAT_ACTION)
        mIntentFilter?.addAction(ClientService.MESSAGE_ACTION)
        mIntentFilter?.addAction(SimpleHttpServer.SERVICE_STATE)
        mIntentFilter?.addAction(SimpleHttpServer.SERVICE_EXCEPTION)
        mIntentFilter?.addAction(ClientService.CONNECT_STATE)
        mReciver = MessageBackReciver()
        mReciver?.let { mIntentFilter?.let { it1 -> mLocalBroadcastManager?.registerReceiver(it, it1) } }


    }

    override fun onDestroy() {
        super.onDestroy()
        if (iBackService != null) {
            activity?.unbindService(conn)

        }
        mReciver?.let { mLocalBroadcastManager?.unregisterReceiver(it) }
    }

    override fun onStop() {
        super.onStop()
    }


    private val conn = object : ServiceConnection {

        override fun onServiceDisconnected(name: ComponentName) {
            iBackService = null

        }

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            iBackService = IBackService.Stub.asInterface(service)
        }
    }

    internal inner class MessageBackReciver() : BroadcastReceiver() {


        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {
                SimpleHttpServer.SERVICE_STATE -> {
                    val b = intent.getBooleanExtra(SimpleHttpServer.SERVICE_STATE, false)
                    if (b) {


                        Log.e(TAG, "服务器打开成功" + NetWorkKit.getLocalIpAddress())
                        btn_cancel.visibility = View.VISIBLE
                        et_port.isEnabled = false
                        btn_ok.visibility = View.GONE
                        btn_cancel.setOnClickListener {
                            shs?.stopAsync()
                        }
                    } else {
                        btn_ok.visibility = View.VISIBLE
                        et_port.isEnabled = true
                        tv_title?.text = "打开服务器"
                        btn_cancel.visibility = View.GONE
                    }

                }
                SimpleHttpServer.SERVICE_EXCEPTION -> {
                    val extra = intent.getStringExtra(SimpleHttpServer.SERVICE_EXCEPTION)
                    ToastU.showToast(extra)
                }

                ClientService.HEART_BEAT_ACTION -> {
                    Log.e(TAG, "收到一个心跳包")
                }

                ClientService.MESSAGE_ACTION -> {

                    val message = intent.getStringExtra(ClientService.MESSAGE_ACTION)
                    val ip = intent.getStringExtra(ClientService.MESSAGE_USER)
                    when (message) {
                        "@恭喜连接成功@" -> {
                            ToastU.showToast("恭喜连接成功")
                        }
                        else->{
                            ToastU.showToast(ip+"："+message)
                        }
                    }
                }
                ClientService.CONNECT_STATE -> {
                    val b = intent.getBooleanExtra(ClientService.CONNECT_STATE, false)
                    if (b) {
                        try {
                            ConnConfig.ip = intent.getStringExtra("ip")
                            ConnConfig.port = intent.getStringExtra("port")
                        } catch (e: Exception) {
                            e.printStackTrace()
                            Log.e(TAG, e.message)
                        }

                        btn_cancel.setOnClickListener {

                            iBackService?.sendMessage("connect_close")

                        }
                    }
                }
            }

        }
    }

    private var mReciver: MessageBackReciver? = null

    private var mIntentFilter: IntentFilter? = null

    private var mLocalBroadcastManager: LocalBroadcastManager? = null
    override fun lazyLoad() {

    }

    private var mTitle: String? = null

    companion object {
        fun getInstance(title: String): SettingF {
            val fragment = SettingF()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }

        private var shs: SimpleHttpServer? = null
        var iBackService: IBackService? = null
    }
}